import * as echarts from 'echarts'
import { onMounted, onUnmounted } from 'vue'
import { debounce } from '@/utils/index.js'

export default function useCharts(elRef, initProps) {
  let chart = null
  onMounted(() => {
    chart = echarts.init(elRef.value)
    chart.setOption(initProps)
    window.addEventListener('resize', defn)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', defn)
    if (chart) {
      echarts.dispose(chart)
      chart = null
    }
  })

  function updateDraw(option) {
    chart && chart.setOption(option)
  }

  function resize() {
    chart && chart.resize()
  }

  let defn = debounce(resize, 500)

  return {
    resize,
    updateDraw,
  }
}
